<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2018/10/24
 * Time: 21:17
 */

namespace app\admin\controller;
use app\admin\model\Translate as Model;
use think\Request;
use think\Db;
/**
 * Class Translate
 * @package app\admin\controller
 * 每日翻译
 */

class Translate extends Admin
{
    /**
     * 主页
     */
    public function index(){
        $map = array();
        $list = $this->lists('Translate',$map);
        int_to_string($list,array(
            'type' => array(1=>"考研",2=>"专升本",3=>"四六级",4=>"雅思",5=>"托福")
        ));
        $this->assign('list',$list);

        return $this->fetch();
    }
    /**
     * 添加
     */
    public function add(){
        if(IS_POST){
            $data = input('post.');
            if(empty($data['id'])) {
                unset($data['id']);
            }
            $Model = new Model();
            if ($data['create_time']){
                $data['create_time'] = strtotime($data['create_time']);
            }
            $result = $Model->where(['type' => $data['type'],'create_time' => $data['create_time']])->field('id')->find();
            if (!empty($result)){
                return ['code' => 0,'msg' => '数据重复，注意类型和日期！'];
            }
            $res = $Model->validate('Translate')->save($data);
            if ($res === false){
                return ['code' => 0,'msg' => $Model->getError()];
            }else{
                return $this->success('添加成功',Url('index'));
            }
        }else{
            $this->assign('msg','');
            return $this->fetch('edit');
        }
    }

    /**
     * 修改
     */
    public function edit(){
        if(IS_POST){
            $data = input('post.');
            $Model = new Model();
            if ($data['create_time']){
                $data['create_time'] = strtotime($data['create_time']);
            }
            $result = $Model->where(['type' => $data['type'],'create_time' => $data['create_time'],'id' => ['neq',$data['id']]])->field('id')->find();
            if (!empty($result)){
                return ['code' => 0,'msg' => '数据重复，注意类型和日期！'];
            }
            $model = $Model->validate('Translate')->save($data,['id'=>$data['id']]);
            if($model){
                return $this->success('修改成功!',Url("index"));
            }else{
                return ['code' => 0,'msg' => '暂无更新，修改失败！'];
            }
        }else{
            //根据id获取课程
            $id = input('id');
            if(empty($id)){
                return $this->error("系统错误,不存在该条数据!");
            }else{
                $msg = Model::get($id);
                $this->assign('msg',$msg);
            }
            return $this->fetch();
        }
    }

    /**
     * 删除
     */
    public function del(){
        $id = input('id');
        if (empty($id)){
            return $this->error("系统参数错误");
        }
        $info = Model::where('id',$id)->delete();
        if($info) {
            $res = Db::name('translate_answer')->where('tid',$id)->field('openid')->find();
            if ($res){
                Db::name('translate_answer')->where('tid',$id)->delete();
            }
            return $this->success("删除成功");
        }else{
            return $this->error("删除失败");
        }
    }
    /**
     * 通讯录excel导入
     */
    public function inserExcel(){
        //引用PHPExcel
        vendor("phpexcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory");
        vendor('phpexcel.Classes.PHPExcel');
        vendor('phpexcel.Classes.PHPExcel.Reader.Excel5');
        vendor('phpexcel.Classes.PHPExcel.Reader.Excel2007');
        //获取表单上传文件
        $file = request() ->file('excel');
        $Info = $file ->getInfo();
        $Ext = explode('.',$Info['name']);
        $ext = $Ext[1];
        $info = $file ->move(ROOT_PATH . 'public' . DS . 'uploads');//上传之后移动地址
        if ($info) {
            $exclePath = $info->getPathName();  //上传文件的地址
            if ($ext == 'xlsx'){
                $objReader = \PHPExcel_IOFactory::createReader('excel2007');
            }else{
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            }
            $obj_PHPExcel = $objReader ->load($exclePath, $encode = 'utf-8');  //加载文件内容,编码utf-8
            $excel_array = $obj_PHPExcel ->getsheet(0) ->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
            $result = $this ->add_excel($excel_array);
            unlink($exclePath);//完成后删除该文件
            return $result;
        } else {
            return $file ->getError();
        }
    }
    /**
     * 通讯录导入处理函数
     */
    public function add_excel($data){
        $user = new Model();  // 标题  类型  日期  内容
        $sum = 0;//记录新增用户记录
        $all = array();
        foreach($data as $k => $v){
            if (empty($v[0]) || empty($v[1]) || empty($v[2]) || empty($v[3])){
                return ['code' => 0, 'msg' => '第' . ($k + 2) . '行缺少字段值!'];
            }else{
                // 监测是否有值  数据库中有值则可以添加  无值不能添加
                $info = [];
                $arr = [
                    '考研' => 1,
                    '专升本' => 2,
                    '四六级' => 3,
                    '雅思' => 4,
                    '托福' => 5
                ];
                if (!isset($arr[$v[1]])){
                    return ['code' => 0, 'msg' => '第' . ($k + 2) . '行 *类型* 字段错误!'];
                }
                $create_time = strtotime($v[2]);
                if ($create_time){
                    if ($create_time < strtotime(date('Y-m-d'))){
                        return ['code' => 0, 'msg' => '第' . ($k + 2) . '行 *日期* 字段值错误!'];
                    }else{
                        $info['create_time'] = $create_time;
                    }
                }else{
                    return ['code' => 0, 'msg' => '第' . ($k + 2) . '行 *日期* 字段值格式错误!'];
                }
                $res = Db::name('translate')->where(['type' => $arr[$v[1]],'create_time' => $create_time])->field('title')->find();
                if ($res){
                    // 值错误
                    return ['code' => 0, 'msg' => '第' . ($k + 2) . '行数据重复!'];
                }else{
                    // 值正确
                    $info['title'] = $v[0];
                    $info['type'] = $arr[$v[1]];
                    $info['create_time'] = $create_time;
                    $info['content'] = $v[3];
                }
                array_push($all, $info);
                $sum++;
            }
        }
        //新增用户保存
        $user ->saveAll($all);
        return  $this ->success("导入成功,新增数据{$sum}个!");
    }
}